package com.zs.chat.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author madison
 * @description
 * @date 2020/10/13 12:41 上午
 */
@Slf4j
@Component
public class WsServer {

    @Value("${netty.port}")
    private int port;

    @PostConstruct
    public void start() {
        log.info("Netty server Starting...");
        EventLoopGroup mainGroup = new NioEventLoopGroup();
        EventLoopGroup subGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap server = new ServerBootstrap();
            server.group(mainGroup, subGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WSServerInitialzer());

            ChannelFuture future = server.bind(port).sync();
            if (future.isSuccess()) {
                log.info("Netty server Start success!");
            }
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("netty server error:", e);
        } finally {
            mainGroup.shutdownGracefully();
            subGroup.shutdownGracefully();
        }
    }
}
